
var pageNum = 1
var pageSize = 10

window.onscroll = function () {

    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

    if (scrollTop > 0) {
        $(".ssv-capture").css("right", 0)
    }

    if ($(window).scrollTop() + $(window).height() == $(document).height()) {
        
        indexOnload(openId,pageNum++,pageSize)
    }
}

//获取当前页面的url
var hrefUrl = window.location.href
//微信config配置
$.ajax({
    type: 'GET',
    url: serverPort + '/ddApi/socialOb/getWxSign?wxUrl=' + hrefUrl,
    dataType: 'json',
    success: function (res) {
        var wxConfig = res.data
        wx.config({
            debug: false,
            appId: 'wx93eac5a248357c96',
            timestamp: wxConfig.timestamp,
            nonceStr: wxConfig.nonceStr,
            signature: wxConfig.signature,
            jsApiList: ['JSAPI', 'getLocation']
        });

        wx.ready(function () {
            onload()
            wxGetLocation()
        });

        wx.error(function () {

        })
    }
})

//从queryz中截取用户code
function getUrlCode() { 
    // 截取url中的code
    var url = location.search
    var theRequest = new Object()
    if (url.indexOf("?") != -1) {
        var str = url.substr(1)
        var strs = str.split("&")
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
        }
    }
    return theRequest
}

//初始化请求数据
function onload() {
    //截取url获取code
    var code = ''
    var local = window.location.href // 获取页面url
    var appid = 'wx93eac5a248357c96'
    code = getUrlCode().code // 截取code
    // var u_msg = sessionStorage.getItem("u_msg")
    if (u_msg) {
        indexOnload(openId)
    } else {
        if (code == null || code === '') { 
            // indexOnload(openId)
            // 如果没有code，请求code
            // getWXuserInfo("011r0uFa1XuLpA03lWIa18Gh1V3r0uFF")
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
        } else {
            getWXuserInfo(code)
        }
    }
}

//获取用户信息
function getWXuserInfo(code) {
    $.ajax({
        type: 'GET',
        url: serverPort + '/ddApi/socialOb/getWxOpenInfo?code=' + code,
        dataType: 'json',
        success: function (res) {
            console.log(res)
            if (res.code === 200) {
                var u_msg = res.data
                var u_msg2 = JSON.stringify(u_msg)
                sessionStorage.setItem("u_msg", u_msg2)

                indexOnload(u_msg.openId,1,10)
                // indexOnload(u_msg.openId,pageNum,pageSize)
            }
        },
        error: function (e) {
            console.log('接口报错')
        }
    })
}

  
//获取用户定位
function wxGetLocation() {
wx.getLocation({
    type: 'wgs84',
    success: function (res) {
        showPosition(res)
    },
});
}

//根据用户经纬度获取用户所在市县
function showPosition(res) {
    var latlon = res.latitude + ',' + res.longitude;
    //baidu
    var url = `http://api.map.baidu.com/geocoder/v2/?ak=C93b5178d7a8ebdb830b9b557abce78b&callback=renderReverse&location=${latlon}&output=json&pois=0`;
    $.ajax({
        type: "GET",
        dataType: "jsonp",
        url: url,
        beforeSend: function () {
            $("#baidu_geo").html('正在定位...');
        },
        success: function (json) {
            if (json.status == 0) {
                var n = json.result.addressComponent

                sessionStorage.setItem("U_location",JSON.stringify(n))
                $("#u_province").text(`${n.province}${n.city}`)
                $("#u_city").text(`${n.city}`)
                
                
                getHourWeather(n.city, res.latitude, res.longitude)
                
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log('获取定位失败')

        }
    })
}

  //初始化请求数据
  function indexOnload(openId,pageNum,pageSize) {
      var params = {
        openId,
        pageNum,
        pageSize
      }
      $.ajax({
          type: "GET",
          url: serverPort + '/ddApi/socialOb/getWeatherRealList',
          dataType: 'json',
          data:params,
          success: function (res) {
              var usersArr = res.data

            console.log(usersArr)
              for (var i = 0; i < usersArr.length; i++) {
                  var usersHtml = `
            <li class='item'>
                <div class='item-content'>  
                    <a href='wather_detail.html?id=${usersArr[i].id}'>
                    <!-- 图片 -->
                    <div class="list-img" style=' vertical-align: bottom;'>
                        <img src="${usersArr[i].weatherPic}" alt="">
                    </div>
                    <!-- 介绍 -->
                    <div class="img-introduce">
                        <p class="time">拍摄于&nbsp;<span>${usersArr[i].picTime}</span></p>
                        <p class="city"><span>${usersArr[i].location}</span></p>
                    </div>
                    <div class="list-hd">
                    <p class='waterID'>${usersArr[i].id}</>
                    <p class='name'><span>${usersArr[i].userName.substring(0,1)}</span>${usersArr[i].userName}</p>
                    <a class='sj-love'>${usersArr[i].supportNum}</a>
                    </a>
                </div>
                </div>
            </li>
        `
                  $(".content-list").append(usersHtml)
              }


          },
          error: function (res) {
              console.log(res)
          }
      })
  }

  //获取当前24小时天气
  function getHourWeather(getCity, getLat, getlon) {
      $.ajax({
          type: "GET",
          url: serverPort + `/ddApi/socialOb/getWeatherData/?city=${getCity}&lat=${getLat}&lon=${getlon}`,
          // async: false,
          dataType: "json",
          success: function (res) {

              var hourWeathersData = res.data.hourWeathers
              var currentWeather = res.data.currentWeather

              var currentWeatherHtml = `
            <div class="left">
            <div class="wd">
                <span>${Math.round(currentWeather.temperature)}</span>
                <div>
                <p>℃</p>
                <p>${switchs(currentWeather.status + '').j}</p>
                </div>
            </div>
            <p class='wind'>${currentWeather.windDirection} ${ currentWeather.windSpeed}</p>
            </div>
            <div class="right-img">
                <img class='wd-img' src="images/ssv_sun.png">
            </div>
            <p class='now-weather'>发布时间：&nbsp;<span>${currentWeather.hour} : 00 </span>点</p>
            `

              $('.hd-banner').append(currentWeatherHtml);


              // 24小时预报模板


              // 循环渲染
              for (let i = 0; i < hourWeathersData.length; i++) {
                  var hourWeathersDataHtml = `
                <li class="swiper-slide">
                    <p>${judgeTime(hourWeathersData[i].hour)}:00</p>
                    <img src="images/${switchs(hourWeathersData[i].status + '').k}.png" alt="">
                    <p><span>${Math.round(hourWeathersData[i].temperature)}</span>℃</p>
                </li>
            `

                  $(".hour24 .swiper-wrapper").append(hourWeathersDataHtml)
              }
              //24小时天气循环开关
              var swiper = new Swiper('.weather-list', {
                  slidesPerView: 4,
                  paginationClickable: true,
                  spaceBetween: 7
              });

          }
      });
  }

  // 实景天气点赞
  $(document).stop().on('touchstart', '.sj-love', function () {

      //获取天气id
      var weatherId = Number($(this).parent().find('.waterID').text().trim())
      var _this = $(this)
        
      //发送ajax 
      $.ajax({
          type: 'POST',
          url: serverPort + '/ddApi/socialOb/supportWeatherReal',
          data: {
              openId,
              weatherId
          },
          dataType: 'json',
          success: function (res) {
              clickStatus = Number(res.data.status)
              //判断是加还是减

              if (clickStatus === 1) {
                  //未点赞
                  _this[0].innerHTML = Number(_this[0].innerHTML) + 1
              } else if (clickStatus === 0) {
                  // 已点赞取消
                  _this[0].innerHTML = Number(_this[0].innerHTML) - 1
              }
          }
      })
  })



